package com.weakteam.mobile.minimum.service;

import android.content.Context;

import com.weakteam.mobile.minimum.state.AppSettings;

import java.lang.ref.WeakReference;

/**
 * Created by Nail Sharipov (nailxsharipov@gmail.com) on 21.10.2014.
 */

public class ServerSession {

    private static ServerSession instance;

    private WeakReference<Context> context;

    private String serverBaseUrl;

    public static ServerSession getInstance(Context context) {
        if (instance == null) {
            instance = new ServerSession(context);
        }
        instance.context = new WeakReference<Context>(context);

        return instance;
    }

    private void setServerBaseUrl(String serverBaseUrl) {
        this.serverBaseUrl = serverBaseUrl;
    }

    private ServerSession(Context context) {
        AppSettings.getInstance().load(context);
        this.setServerBaseUrl(AppSettings.getInstance().getServerBaseUrl());
    }

    public <T extends AsyncRequest> T buildAsyncRequest(Class<T> taskClass) {
        T asyncRequest = null;
        try {
            asyncRequest = taskClass.newInstance();
            asyncRequest.setContext(this.context);
            asyncRequest.setBaseUrl(this.serverBaseUrl);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return asyncRequest;
    }

}
